package com.caigou.comm.base.utils

import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.caigou.comm.R

/**
 * @author #Suyghur.
 * Created on 2021/09/16
 */
object ImageLoader {
    /**
     * 加载图片
     */
    fun load(context: Context, url: String?, view: ImageView) {
        Glide.with(context).clear(view)
        val options = RequestOptions().diskCacheStrategy(DiskCacheStrategy.DATA).placeholder(R.drawable.comm_placeholder)
        Glide.with(context)
            .load(url)
            .transition(DrawableTransitionOptions().crossFade())
            .apply(options)
            .into(view)
    }

    fun loadCircle(context: Context, url: String?, view: ImageView) {
        Glide.with(context).clear(view)
        val options = RequestOptions().diskCacheStrategy(DiskCacheStrategy.DATA).placeholder(R.drawable.comm_placeholder)
        Glide.with(context)
            .load(url)
            .transition(DrawableTransitionOptions().crossFade())
            .apply(options)
            .apply(RequestOptions.bitmapTransform(CircleCrop()))
            .into(view)
    }

    fun assertValidRequest(context: Context): Boolean {
        if (context is Activity) {
            return !isDestroy(context)
        } else if (context is ContextWrapper) {
            if (context.baseContext is Activity) {
                return !isDestroy((context.baseContext) as Activity)
            }
        }
        return true
    }

    private fun isDestroy(activity: Activity?): Boolean {
        return if (activity == null) {
            true
        } else {
            activity.isFinishing || activity.isDestroyed
        }
    }
}